package com.lazason.wib4android;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import weibo4andriod.Status;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class PostWeiboActivity extends BasicActivity implements OnClickListener {

	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
	private static final int REQ_CODE_PICTURES = 1000;
	private static final int REQ_CODE_CAMERA = 1001;
	private String photoTemp;
	private ArrayList<String> matches;
	private ListView mList;
	private EditText editText;
	TextView sucess;
	private Button post;
	private Button photoButton;
	private ImageView photo;
	private String imagePath;
	private String cachePaht;
	private String currentPhoto;
	private ProgressDialog m_ProgressDialog = null;
	private Runnable postThread;
	Thread thread;

	/**
	 * Called with the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyApplication.getInstance().addActivity(this);
		// Inflate our UI from its XML layout description.
		setContentView(R.layout.post);
		cachePaht = this.getExternalCacheDir().toString();
		// Get display items for later interaction
		Button speakButton = (Button) findViewById(R.id.btn_speak);
		photo = (ImageView) findViewById(R.id.photo1);
		editText = (EditText) findViewById(R.id.editText1);
		photoButton = (Button) findViewById(R.id.btn_photo);
		mList = (ListView) findViewById(R.id.speechlist);
		post = (Button) findViewById(R.id.btn_submit);
		postThread = new Runnable() {
			@Override
			public void run() {
				postWeibo();
			}
		};

		post.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				Weibo weibo = OAuthConstant.getInstance().getWeibo();
				String text = "";
//
//				thread = new Thread(null, postThread, "postWeiboThread");
//				thread.start();
				PostTask postTask = new PostTask();
				postTask.execute();
				m_ProgressDialog = ProgressDialog.show(PostWeiboActivity.this,
						"Please wait...", "Uploading data ...", true,true);
				// 设置ProgressDialog 是否可以按退回按键取消
				m_ProgressDialog.setCancelable(true);

			}

		});

		photoButton.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {

				try {
					Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
					startActivityForResult(i, REQ_CODE_CAMERA);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
		mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> paramAdapterView,
					View paramView, int paramInt, long paramLong) {
				int start = editText.getSelectionStart();
				int end = editText.getSelectionEnd();
				editText.getText().replace(Math.min(start, end),
						Math.max(start, end), matches.get(paramInt), 0,
						matches.get(paramInt).length());

				// editText.setText(matches.get(paramInt));

			}
		});
		// Check to see if a recognition activity is present
		PackageManager pm = getPackageManager();

		List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
				RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		if (activities.size() != 0) {
			speakButton.setOnClickListener(this);
		} else {
			speakButton.setEnabled(false);
			speakButton.setText("Recognizer not present");
		}

	}

	/**
	 * Handle the click on the start recognition button.
	 */
	public void onClick(View v) {
		if (v.getId() == R.id.btn_speak) {
			startVoiceRecognitionActivity();
		}
	}

	/**
	 * Fire an intent to start the speech recognition activity.
	 */
	private void startVoiceRecognitionActivity() {
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
				"Speech recognition demo");
		startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
	}

	/**
	 * Handle the results from the recognition activity.
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode ==
		// RESULT_OK) {
		// // Fill the list view with the strings the recognizer thought it
		// could have heard
		// matches = data.getStringArrayListExtra(
		// RecognizerIntent.EXTRA_RESULTS);
		// mList.setAdapter(new ArrayAdapter<String>(PostWeiboActivity.this,
		// android.R.layout.simple_list_item_1,
		// matches));
		//
		// }
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case VOICE_RECOGNITION_REQUEST_CODE:
				matches = data
						.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
				mList.setAdapter(new ArrayAdapter<String>(
						PostWeiboActivity.this,
						android.R.layout.simple_list_item_1, matches));
				break;
			case REQ_CODE_CAMERA:
				Bitmap bm = (Bitmap) data.getExtras().get("data");
				photo.setImageBitmap(bm);// 想图像显示在ImageView视图上，private ImageView
											// img;
				long time = System.currentTimeMillis();
				currentPhoto = String.valueOf(time) + ".jpg";
				File myCaptureFile = new File(cachePaht, currentPhoto);
				try {
					BufferedOutputStream bos = new BufferedOutputStream(
							new FileOutputStream(myCaptureFile));
					/* 采用压缩转档方法 */
					bm.compress(Bitmap.CompressFormat.JPEG, 70, bos);

					/* 调用flush()方法，更新BufferStream */
					bos.flush();

					/* 结束OutputStream */
					bos.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				uploadImage(photoTemp);
				break;
			case REQ_CODE_PICTURES:
				Uri uri = data.getData();
				ContentResolver cr = this.getContentResolver();
				// get the physical path of the image
				Cursor c = cr.query(uri, null, null, null, null);
				c.moveToFirst();
				photoTemp = c.getString(c.getColumnIndex("_data"));
				uploadImage(photoTemp);
				break;
			default:
				break;
			}
			;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		MyApplication.getInstance().removeActivity(this);

	}

	private void openPictures() {
		Intent intent = new Intent();
		/* Open the page of select pictures and set the type to image */
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, REQ_CODE_PICTURES);
	}

	protected void uploadImage(String path) {

	}

	private void postWeibo() {
		Weibo weibo = OAuthConstant.getInstance().getWeibo();
		String text = "";
		try {

			if (currentPhoto != null) {
				File pic = new File(cachePaht, currentPhoto);
				Status status = weibo.uploadStatus(editText.getText()
						.toString(), pic);

			} else {
				Status status = weibo.updateStatus(editText.getText()
						.toString());

			}

			text = "发送成功";
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			text = "发送失败";
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			text = "发送失败";
		} finally {
			Toast toast = Toast.makeText(PostWeiboActivity.this, text,
					Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	private class PostTask extends AsyncTask<Void, Void, Integer> {

		protected Integer doInBackground(Void... page) {
			Weibo weibo = OAuthConstant.getInstance().getWeibo();
			try {

				if (currentPhoto != null) {
					File pic = new File(cachePaht, currentPhoto);
					weibo4andriod.Status status = weibo.uploadStatus(editText.getText()
							.toString(), pic);

				} else {
					weibo4andriod.Status status = weibo.updateStatus(editText.getText()
							.toString());

				}
 
			} catch (WeiboException e) {
			 
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			 
			} 
			return new Integer(1);
		}

		protected void onPostExecute(Integer parms) {
			
			Intent mentionIntent = new Intent(); 
			mentionIntent.setClass(PostWeiboActivity.this, HomeActivity.class);
			m_ProgressDialog.cancel();
			m_ProgressDialog.dismiss();
			startActivity(mentionIntent);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// listView.addFooterView(layout);
		}

	}
}